#include "pch.hpp"
#include "ScriptEditWindow.hpp"

using namespace Engine;
using namespace Engine::Edit;




ScriptEditWindow::ScriptEditWindow(Script::ptr script, QWidget* parent)
	: DocumentWindow(script, parent)
	, m_script(script)
{
	ui.setupUi(this);

	//
	// TextEdit
	//

	m_highlighter = boost::make_shared<AngelscriptHighlighter>(ui.textEdit->document(), m_errors);
	QFont font = m_highlighter->font();
	ui.textEdit->setTabStopWidth(font.pointSize() * 3);
	ui.textEdit->setFocus(Qt::OtherFocusReason);


	//
	// LineView
	//

	ui.numberView->setTextEdit(ui.textEdit);


	//
	// Signals
	//

	verify(connect(ui.textEdit, SIGNAL(textChanged()), SLOT(onTextChanged())));


	setTitle();

	QString content = script->content();
	ui.textEdit->document()->setPlainText(content);
}
///////////////////////////////////////////////////////////////////////////////////////////////////

ScriptEditWindow::~ScriptEditWindow()
{}
///////////////////////////////////////////////////////////////////////////////////////////////////




Script::ptr ScriptEditWindow::script() const
{
	return m_script;
}
///////////////////////////////////////////////////////////////////////////////////////////////////

QString ScriptEditWindow::contents() const
{
	return ui.textEdit->document()->toPlainText();
}
///////////////////////////////////////////////////////////////////////////////////////////////////

ErrorModel::ptr ScriptEditWindow::errorModel() const
{
	return m_errors;
}
///////////////////////////////////////////////////////////////////////////////////////////////////

void ScriptEditWindow::changeState(State::Type state)
{
	__super::changeState(state);

	switch(state)
	{
	case State::Editing:
		ui.textEdit->setReadOnly(false);
		break;
	case State::Debugging:
		ui.textEdit->setReadOnly(true);
		break;
	default:
		throw invalid_value_exception(state);
	}
}
///////////////////////////////////////////////////////////////////////////////////////////////////




void ScriptEditWindow::onTextChanged()
{
	QString text = contents();

	// We must compare the plain text against the stored one:
	// textChanged is emitted when the Highlighter kicks in, but
	// this does not quality for a modified document
	if(text != m_script->content())
	{
		setWindowModified(true);
		emit modified(this);
	}
	// If the user changes the text back to the state it had before the last
	// save, then the document is not modified
	else
	{
		setWindowModified(false);
		emit modified(this);
	}
}
///////////////////////////////////////////////////////////////////////////////////////////////////

void ScriptEditWindow::save()
{
	auto content = ui.textEdit->document()->toPlainText();
	m_script->setContent(content);

	setWindowModified(false);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
